Now that we have our Promise set up, we can load in the request module on top of
the code, creating a constant called request and setting that equal to the return
result from require('request'):
const request = require('request');
var geocodeAddress = (address) => {
Next, we'll move into the geocode.js file, grab code inside the geocodeAddress
function, and move it over into promise-2 file, inside of the constructor function:
const request = require('request');
var geocodeAddress = (address) => {
return new Promise((resolve, reject) => {
var encodedAddress = encodeURIComponent(address);
request({
url: `https://maps.googleapis.com/maps/api/geocode/json?address=${encodedAddress}`,
json: true
}, (error, response, body) => {
if (error) {
callback('Unable to connect to Google servers.');
} else if (body.status === 'ZERO_RESULTS') {
callback('Unable to find that address.');
} else if (body.status === 'OK') {
callback(undefined, {
address: body.results[0].formatted_address,
latitude: body.results[0].geometry.location.lat,
longitude: body.results[0].geometry.location.lng
});
}
});
});
};
Now we are mostly good to go; we only need to change a few things. The first
thing we need to do is to replace our error handlers. In the if block of the code,
we have called our callback handler with one argument; instead, we'll call reject,
because if this code runs, we want to reject the promise. We have the same thing
in the next else block. We'll call reject if we get ZERO_RESULTS. This is indeed a
failure, and we do not want to pretend we succeeded:
if (error) {
reject('Unable to connect to Google servers.');
} else if (body.status === 'ZERO_RESULTS') {
reject('Unable to find that address.');
Now in the next else block, this is where things did go well; here we can call
resolve. Also, we can remove the first argument, as we know resolve and reject
only take one argument: